package com.dabai.markdownq.ui;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;

import androidx.appcompat.app.AlertDialog;

import com.dabai.dbutils.dialog.MdcDialog;
import com.dabai.dbutils.toast.DBToast;
import com.dabai.dbutils.utils.AndroidUtils;
import com.dabai.dbutils.utils.DateUtils;
import com.dabai.dbutils.utils.FileUtils;
import com.dabai.dbutils.utils.PrinterUtils;
import com.dabai.dbutils.utils.ShareUtils;
import com.dabai.dbutils.utils.SharedPreferencesBasicUse;
import com.dabai.dbutils.utils.SharedPreferencesUtils;
import com.dabai.markdownq.R;
import com.dabai.markdownq.databinding.ActivityMarkdownParsBinding;
import com.dabai.markdownq.other.ColorData;
import com.dabai.markdownq.utils.OtherUtils;
import com.dabai.uitools.base.BackGestureBaseActivity;
import com.dabai.uitools.utils.ViewUtils;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.permissionx.guolindev.PermissionX;
import com.watermark.androidwm_light.WatermarkBuilder;
import com.watermark.androidwm_light.bean.WatermarkText;

import java.io.File;
import java.util.Objects;


public class MarkdownParsActivity extends BackGestureBaseActivity {

    Context context;
    ActivityMarkdownParsBinding ampb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ampb = ActivityMarkdownParsBinding.inflate(getLayoutInflater());
        setContentView(ampb.getRoot());

        context = this;

        setNeedBackGesture(true);

        SharedPreferencesBasicUse.init(context);

        Intent intent = getIntent();
        String originalContent = intent.getStringExtra("originalContent");
        String title = intent.getStringExtra("title");
        setTitle("预览 - " + title);

        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);

        OtherUtils.parseMd(context, ampb.MdTextView2, originalContent + '\u3000');

        int color = SharedPreferencesBasicUse.getInt("MdBackColor", Color.WHITE);
        ampb.MdTextView2.setBackgroundColor(color);
        ampb.nestedScrollView.setBackgroundColor(color);


        if (SharedPreferencesUtils.getDefaultSharedPreferences(context).getBoolean("customFont", false)) {

            File fontFile = new File(OtherUtils.getFontDir(context), "font.ttf");
            if (fontFile.exists()) {
                //如果字体存在
                try {
                    Typeface typeface = Typeface.createFromFile(fontFile);
                    ampb.MdTextView2.setTypeface(typeface);
                } catch (Exception e) {
                    //如果发生意外,就删除损坏字体
                    DBToast.showText(context, "自定义字体加载失败,已自动还原!", false);
                    FileUtils.delete(fontFile);
                }
            }

        }

        if (SharedPreferencesUtils.getDefaultSharedPreferences(context).getBoolean("textOptional", false)) {
            ampb.MdTextView2.setTextIsSelectable(true);
        }


    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        switch (itemId) {
            case R.id.print:

                Bitmap bitmap1 = ViewUtils.getBitmapByView(ampb.MdTextView2);//iv是View

                PrinterUtils.printBitmap(context
                        , "" + getIntent().getStringExtra("title")
                        , bitmap1);

                break;
            case R.id.backgroundPic:


                MdcDialog.showColorChooseDialog(context, "自定义稿纸颜色", ColorData.writingPaperColor, new MdcDialog.OnColorChooseListener() {
                    @Override
                    public void confirm(AlertDialog dialog, int color, String colorText) {
                        ampb.MdTextView2.setBackgroundColor(color);
                        ampb.nestedScrollView.setBackgroundColor(color);
                        SharedPreferencesBasicUse.setInt("MdBackColor", color);

                        dialog.dismiss();
                    }

                    @Override
                    public void parseError(AlertDialog dialog, String colorText) {
                        DBToast.showText(context, "这个颜色不可使用!", false);
                    }
                }).getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_IOS);

                break;
            case android.R.id.home:
                finish();
                if (SharedPreferencesUtils.getDefaultSharedPreferences(context).getBoolean("animatedTransitions", false)) {
                    overridePendingTransition(com.dabai.uitools.R.anim.push_ios_in, com.dabai.uitools.R.anim.push_ios_out);
                }
                break;
            case R.id.sharePhoto:
                if (getIntent().getStringExtra("originalContent").isEmpty()) {
                    DBToast.showYellowToast(context, "啥也没有~");
                    return true;
                }

                Bitmap bitmap = ViewUtils.getBitmapByView(ampb.MdTextView2);

                View diaView = LayoutInflater.from(context).inflate(com.dabai.dbutils.R.layout.dialog_save_image, null);
                ImageView imageView = diaView.findViewById(com.dabai.dbutils.R.id.imageView);

                if (SharedPreferencesUtils.getDefaultSharedPreferences(context).getBoolean("customWatermark", false)) {

                    WatermarkText watermarkText = new WatermarkText(SharedPreferencesBasicUse.getString("watermarkText", "默认水印"))
                            .setPositionX(0.5)
                            .setPositionY(0.5)
                            .setTextColor(Color.DKGRAY)
                            .setTextFont(R.font.googlesan)
                            .setTextAlpha(60)
                            .setRotation(30)
                            .setTextSize(30);

                    bitmap = WatermarkBuilder
                            .create(context, bitmap)
                            .setTileMode(true)
                            .loadWatermarkText(watermarkText)
                            .getWatermark()
                            .getOutputImage();
                }


                imageView.setImageBitmap(bitmap);

                Bitmap finalBitmap = bitmap;
                new MaterialAlertDialogBuilder(this)
                        .setTitle("保存图片")
                        .setView(diaView)
                        .setPositiveButton("保存图片", (dialog, which) -> {

                            if (AndroidUtils.isAboveIsEqualToTheAndroidQ()) {
                                boolean isOk = FileUtils.saveBitmapToDCIM(context, finalBitmap, "MarkdownQ", "MarkdownQ_" + DateUtils.getNowTime(4));
                                DBToast.showText(context, isOk ? "保存成功!" : "保存失败!", isOk);
                            } else {
                                PermissionX.init(this)
                                        .permissions(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                        .request((allGranted, grantedList, deniedList) -> {
                                            if (allGranted) {
                                                boolean isOk = FileUtils.saveBitmapToDCIM(context, finalBitmap, "MarkdownQ", "MarkdownQ_" + DateUtils.getNowTime(4));
                                                DBToast.showText(context, isOk ? "保存成功!" : "保存失败!", isOk);
                                            } else {
                                                DBToast.showText(context, "需要储存权限!", false);
                                            }
                                        });
                            }
                        })
                        .setNegativeButton("分享图片", (dialog, which) -> {
                            ShareUtils.shareSingleImage(context, finalBitmap);
                        })
                        .setNeutralButton("取消", null)
                        .show().getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_IOS);

                break;
            default:

                break;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.pars, menu);
        return super.onCreateOptionsMenu(menu);
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (SharedPreferencesUtils.getDefaultSharedPreferences(context).getBoolean("animatedTransitions", false)) {
            overridePendingTransition(com.dabai.uitools.R.anim.push_ios_in, com.dabai.uitools.R.anim.push_ios_out);
        }
    }
}